package org.gongliang.jsmile.config.excel;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import jodd.bean.BeanUtil;

/**
 * @category excel导入工具
 * @author 龚亮
 * @date 2016-10-14 14:03:21
 */
@SuppressWarnings("all")
public class PoiImporter {


	// 导入的文件
	private InputStream srcFile;
	private ImportParams importParams;


	public PoiImporter(InputStream srcFile) {
		this.srcFile = srcFile;
	}

	public static PoiImporter init(InputStream srcFile) {
		return new PoiImporter(srcFile);
	}

	/**
	 * 导出excel,返回sheet对应的list集合
	 */
	public <T> List<T> readExcel(Class<T> clazz) throws Exception {
		Preconditions.checkArgument(importParams.getColumns() != null && importParams.getColumns().length > 0,
				"columns不能为空并且长度必须大于0");
		Preconditions.checkNotNull(srcFile, "srcFile不能为空!");
		Workbook wb = null;
		try {
			wb = WorkbookFactory.create(srcFile);
		} catch (Exception e) {
			throw new RuntimeException("srcFile:文件出错.");
		}
		List<T> data = Lists.newArrayList();
		Sheet sheet = wb.getSheetAt(importParams.getSheetNum());
		for (int j = importParams.getHeaderRow(); j < sheet.getLastRowNum() + importParams.getHeaderRow(); j++) {
			Object entity = null;
			if (Map.class.equals(clazz)) {
				entity = Maps.newHashMap();
			} else {
				entity = clazz.newInstance();
			}
			Row row = sheet.getRow(j);
			int cellNum = row.getLastCellNum();
			for (int cellIndex = row.getFirstCellNum(); cellIndex < cellNum; cellIndex++) {
				Cell cell = row.getCell(cellIndex);
				String name = importParams.getColumns()[cellIndex];
				BeanUtil.declared.setProperty(entity, name, getCellValue(name, cell, entity));
			}
			data.add(clazz.cast(entity));
		}
		return data;
	}

	/**
	 * 获取每一个单元格的值
	 */
	private Object getCellValue(String name, Cell cell, Object entity) {
		Object value = null;
		if (cell != null && !cell.equals(" ")) {
			cell.setCellType(CellType.STRING);
			value = cell.getStringCellValue();
			if (importParams.getFilter() != null) {
				value = importParams.getFilter().doFilter(name, cell.getStringCellValue().replace(" ", ""), entity);
			}
		}
		return value;
	}

	public PoiImporter importParams(ImportParams importParams) {
		this.importParams = importParams;
		return this;
	}

}
